import react from '@vitejs/plugin-react-swc';
import { defineConfig } from 'vite';
import monkey, { cdn } from 'vite-plugin-monkey';
import inject from '@rollup/plugin-inject';
import path from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    inject({
      $: "jquery",
      jQuery: "jquery",
      "windows.jQuery": "jquery",
    }),
    {
      name: 'pre-url-origin',
      apply: 'serve',
      config() {
        const origin = `http://127.0.0.1:5173`;
        const urlReg = /\burl\((['"])(\/[^\/])/g;
        return {
          css: {
            postcss: {
              plugins: [
                {
                  postcssPlugin: 'postcss-pre-url-origin',
                  Declaration(decl) {
                    if (urlReg.test(decl.value)) {
                      decl.value = decl.value.replaceAll(
                        urlReg,
                        `url($1${origin}$2`
                      );
                    }
                  },
                },
              ],
            },
          },
        };
      },
    },
    monkey({
      entry: 'src/main.tsx',
      userscript: {
        name: "TamperMonkey-Ys4funTools",
        author: "MakoStar",
        match: ['*://bbs.ys4fun.com/*'],
        icon: 'https://www.google.com/s2/favicons?sz=64&domain=ys4fun.com',
        namespace: 'https://gitee.com/makostar/TamperMonkey-Ys4funTools',
        description: "The website bbs.ys4fun.com script tools."
      },
      build: {
        externalGlobals: {
          react: cdn.jsdelivr('React', 'umd/react.production.min.js'),
          'react-dom': cdn.jsdelivr('ReactDOM','umd/react-dom.production.min.js'),
          jquery: cdn.jsdelivr("jQuery", "dist/jquery.min.js"),
        },
      },
    }),
  ],
  build: {
    minify: true,
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
      "@assets": path.resolve(__dirname, "./src/assets"),
      "@components": path.resolve(__dirname, "./src/components"),
      "@configs": path.resolve(__dirname, "./src/configs"),
      "@constants": path.resolve(__dirname, "./src/constants"),
      "@contexts": path.resolve(__dirname, "./src/contexts"),
    }
  }
});
